#pragma once
#include<iostream>
using namespace std;

template<class K>
struct BSTreeNode
{
	struct BSTreeNode<K>* _left;
	struct BSTreeNode<K>* _right;
	K _key;

	BSTreeNode(const K& key)
		:_left(nullptr),_right(nullptr),_key(key)
	{}
};

template<class K>
class BSTree
{
public:
	typedef BSTreeNode<K> Node;

	bool Insert(const K& key)
	{
		if (_root == nullptr)
		{
			_root = new Node(key);
			return true;
		}

		Node* parent = nullptr;
		Node* cur = _root;
		while (cur)
		{
			if (cur->_key < key)
			{
				parent = cur;
				cur = cur->_right;
			}
			else if (cur->_key > key)
			{
				parent = cur;
				cur = cur->_left;
			}
			else
			{
				return false;
			}
		}
		cur = new Node(key);
		if (parent->_key < key)
		{
			parent->_right = cur;
		}
		else
		{
			parent->_left = cur;
		}

		return true;
	}

	bool Find(const K& key)
	{
		Node* cur = _root;
		while (cur)
		{
			if (cur->_key < key)
			{
				cur = cur->_right;
			}
			else if (cur->_key > key)
			{
				cur = cur->_left;
			}
			else
			{
				return true;
			}
		}
		return false;
	}

	bool erase(const K& key)
	{
		if (_root == nullptr)
		{
			return false;
		}

		Node* cur = _root;
		Node* parent = cur;
		while (cur)
		{
			if (cur->_key < key)
			{
				parent = cur;
				cur = cur->_right;
			}
			else if (cur->_key > key)
			{
				parent = cur;
				cur = cur->_left;
			}
			else
			{
				if (cur->_left == nullptr)
				{
					if (parent == cur)
					{
						_root = parent->_right;
					}
					else
					{
						if (cur == parent->_right)
						{
							parent->_right = cur->_right;
						}
						else
						{
							parent->_left = cur->_right;
						}
					}
					delete cur;
				}
				else if (cur->_right == nullptr)
				{
					if (parent == cur)
					{
						_root = parent->_left;
					}
					else
					{
						if (cur == parent->_right)
						{
							parent->_right = cur->_left;
						}
						else
						{
							parent->_left = cur->_left;
						}
					}
					delete cur;
				}
				else
				{
					Node* RightMin = cur->_right;
					Node* RigthtMinParent = cur;

					while (RightMin->_left)
					{
						RigthtMinParent = RightMin;
						RightMin = RightMin->_left;
					}

					swap(RightMin->_key, cur->_key);

					if (RigthtMinParent->_right == RightMin)
					{
						RigthtMinParent->_right = RightMin->_right;
					}
					else
						RigthtMinParent->_left = RightMin->_right;

					delete RightMin;
				}
				return true;
			}
		}

		return false;
	}

	void InOrder()
	{
		InOrder(_root);
	}

	void PostOrder()
	{
		PostOrder(_root);
	}

private:
	void InOrder(Node* root)
	{
		if (root == nullptr)
		{
			return;
		}

		InOrder(root->_left);
		cout << root->_key << " ";
		InOrder(root->_right);
	}

	void PostOrder(Node* root)
	{
		if (root == nullptr)
		{
			return;
		}

		InOrder(root->_left);
		InOrder(root->_right);
		cout << root->_key << " ";
	}

private:
	Node* _root = nullptr;
};
